<template>
  <div @submit="handleSubmit">
    <a-form :form="form">
      <!--companyId-->
      <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="所属公司">
        <a-select
          :disabled="isDisabled"
          @change="handleProvinceChange"
          v-decorator="[ 'companyId',{rules: [{ required: true, message: '请选择所属公司' }],initialValue: defaultCompany}]"
          placeholder="请选择所属公司">
          <a-select-option :value="company.id" v-for="company in companyList" :key="company.id">
            {{company.name}}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="类别">
        <a-select
          v-decorator="[ 'categoryId', {rules: [{ required: true, message: '请选择所属类别' }]}]"
          placeholder="请选择所属类别">
          <a-select-option :value="category.id" v-for="category in categoryList" :key="category.id">
            {{category.name}}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="适用商户">
        <a-tree-select
          style="width: 300px"
          :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder='请选择商户'
          allowClear
          treeDefaultExpandAll
          :treeData="treeData"
          v-model="value"

        >
          <span style="color:#08c" slot="title" slot-scope="{key}">
            {{value}}
          </span>>
        </a-tree-select>
      </a-form-item>

      <!--<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商户id">
        <a-input placeholder="微信子商户id"
                 v-decorator="[ 'subMchId',{rules: [{ required: true, message: '请输入微信子商户id' }]}]"
        ></a-input>
      </a-form-item>-->

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品名称">
        <a-input placeholder="商品名称"
                 v-decorator="[ 'name', {rules: [{ required: true, message: '请输入商品名称' }]}]"
        ></a-input>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品编码">
        <a-input placeholder="商品编码"
                 v-decorator="[ 'productNo', {rules: [{ required: true, message: '请输入商品编码' }]}]"
        ></a-input>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="类型">
        <a-radio-group @change="onchange" v-decorator="[ 'type', {rules: [{ required: true, message: '请选择' }]}]">
          <a-radio :value="1">商品</a-radio>
          <a-radio :value="2">收费优惠卷</a-radio>
          <a-radio :value="3">积分兑换</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item v-if="setHide" :labelCol="labelCol" :wrapperCol="wrapperCol" label="优惠卷批次号">
        <a-input placeholder="优惠卷批次号"
                 v-decorator="[ 'stockId',{rules: [{ required: true, message: '请输入优惠卷批次号'}]},]"
        ></a-input>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品金额">
        <a-input placeholder="商品金额"
                 v-decorator="[ 'value', {rules: [{ required: true, message: '请输入商品金额(仅限数字)',pattern: new RegExp(/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/) }]}]"
        ></a-input>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="获取到的积分">
        <a-input placeholder="获取到的积分"
                 v-decorator="[ 'points', {rules: [{ required: true, message: '请输入获取到的积分', pattern: new RegExp(/^[0-9]\d*$/,'g')}]}]"
        ></a-input>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="数量">
        <a-input placeholder="数量"
                 v-decorator="[ 'productCount', {rules: [{ required: true, message: '请输入商品数量(仅限数字)',pattern: new RegExp(/^[1-9]\d*$/,'g') }]}]"
        ></a-input>
      </a-form-item>

      <!--       :format="dateFormat"-->
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="有效时间">
        <a-range-picker

          v-decorator="[ 'validTime', {rules: [{ required: true, message: '请选择时间' }]}]"
        />
      </a-form-item>

      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="商品图"
      >
        <a-upload
          :action="this.$baseURL+'/common/upload/uploadImg'"
          listType="picture-card"
          :fileList="fileList"
          @preview="uploadPreview"
          @change="uploadChange"
        >
          <div v-if="fileList.length < 1">
            <a-icon type="plus"/>
            <div class="ant-upload-text">上传商品图</div>
          </div>
        </a-upload>
        <a-modal :visible="previewVisible" @cancel="uploadCancel">
          <img alt="example" style="width:100%" :src="previewImage"/>
        </a-modal>
      </a-form-item>



      <!--note 简介描述 -->
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="简介描述">
        <!--v-model="content"-->
        <quill-editor
          v-model="content "
          ref="myQuillEditor"
          :options="editorOption"
          @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
          @change="onEditorChange($event)">
        </quill-editor>
      </a-form-item>

      <a-form-item
        v-bind="buttonCol"
      >
        <a-row>
          <a-col span="6">
            <a-button type="primary" html-type="submit">提交</a-button>
          </a-col>
          <a-col span="10">
            <a-button @click="handleGoBack">返回</a-button>
          </a-col>
          <a-col span="8"></a-col>
        </a-row>
      </a-form-item>

    </a-form>
  </div>
</template>

<script>

  import pick from 'lodash.pick'
  import {
    selectAll,
    selectByCompanyId,
    save,
    selectStoreById,
    selectAllCategory
  } from '@/api/commodityService/commodity'
  import { quillEditor } from 'vue-quill-editor'
  import moment from 'moment'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'

  export default {
    components: {
      quillEditor
    },
    props: {
      record: {
        default: ''
      }
    },
    data() {

      return {
        setHide: false,
        dateFormat: 'YYYY/MM/DD',
        value: [],
        treeData: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        buttonCol: {
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 12, offset: 5 }
          }
        },
        storeId: '',
        isDisabled: '',
        companyList: [],
        visible: false,
        form: this.$form.createForm(this),
        merchantList: [],
        categoryList: [],
        defaultMerchant: [],
        previewImage: '',
        previewVisible: false,
        mode: 'multiple',
        defaultCompany: '',
        //图片上传
        fileList: [],
        productPicUrl: '',
        editorOption: {
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike', 'clean'],
              ['blockquote', 'code-block'],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              [{ 'script': 'sub' }, { 'script': 'super' }],
              [{ 'indent': '-1' }, { 'indent': '+1' }],
              [{ 'direction': 'rtl' }],
              [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
              [{ 'color': [] }, { 'background': [] }]
            ]
          }
        },
        content: '',
        validTime: []
      }
    },
    watch: { //商户id
      value(value) {
        var arrs = value.split('-')
        this.storeId = arrs[arrs.length - 1]
      }
    },
    created() {
      this.getAllCompany()
      this.loadEditInfo(this.record)
    },
    mounted() {
    },
    methods: {
      handleGoBack() {
        this.$emit('onGoBack')
      },
      getAllCompany: function() { //查询公司
        const _this = this
        selectAll().then(res => {
          if (res.code === 200) {
            this.companyList = res.result
            let defaultCompany = this.companyList[0].id
            // this.getAllMerchant(_this.record.companyId)
          } else {
            this.$notification.error({
              message: '错误',
              description: res.message,
              duration: 4
            })
          }
        })
      },
      onEditorBlur() {
      }, // 失去焦点事件
      onEditorFocus() {
      }, // 获得焦点事件
      onEditorChange() {
      }, // 内容改变事件
      // 转码
      escapeStringHTML(str) {
        str = str.replace(/&lt;/g, '<')
        str = str.replace(/&gt;/g, '>')
        return str
      },
      //公司改变
      handleProvinceChange(value) {
        if (value) {
          this.getAllMerchant(value)
          this.getAllCategory(value)
        }
      },
      getAllCategory: function(value) {//查询类别列表
        const _this = this
        selectAllCategory(value).then(res => {
          if (res.code === 200) {
            _this.categoryList = res.result
          } else {
            this.$notification.error({
              message: '错误',
              description: res.message,
              duration: 4
            })
          }
        })
      },
      getAllMerchant: function(companyId) {//查询商户
        const _this = this
        selectByCompanyId(companyId).then(res => {
          if (res.code === 200) {
            _this.treeData = res.result
            _this.value = this.record.code
          } else {
            this.$notification.error({
              message: '错误',
              description: res.message,
              duration: 4
            })
          }
        })
      },
      uploadCancel() {
        this.previewVisible = false
      },
      uploadPreview(file) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
      },
      uploadChange(info) {
        const _this = this
        _this.fileList = info.fileList
        if (info.file.status === 'done') {
          _this.fileList.pop()
          _this.fileList.push(info.file)
          _this.productPicUrl = info.file.response.url
          this.$message.success(`${info.file.name} 上传成功`)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败`)
        } else if (info.file.status === 'removed') {
          deletePic(info.file.uid).then(res => {
          })
        }
      },
      loadEditInfo(record) {
        this.couponInfo = record
        this.isDisabled = true
        if (record.type == 2) {
          this.setHide = true
        } else {
          this.setHide = false
        }
        this.fileList = [{ 'uid': '123', 'url': record.productPicUrl.toString(), 'name': '123' }]
        this.content = this.escapeStringHTML(record.note)
        this.getAllMerchant(record.companyId)
        this.getAllCategory(record.companyId)
        this.validTime.push(moment(record.beginTime))
        this.validTime.push(moment(record.endTime))
        record.validTime = this.validTime
        // record.validTime = this.validTime
        record.value = record.value * 0.01
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(record, ['companyId', 'name', 'productNo', 'type', 'subMchId', 'stockId', 'value', 'points', 'productCount', 'validTime', 'categoryId']))
        })
      },
      onchange(e) {
        if (e.target.value == 2) {
          this.setHide = true
        } else {
          this.setHide = false
        }

      },
      handleSubmit() {
        const _this = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!_this.productPicUrl) {
            values.productPicUrl = _this.fileList[0].url
          } else {
            values.productPicUrl = _this.productPicUrl
          }
          // values.productPicUrl   = _this.productPicUrl
          values.storeId = this.storeId
          // 验证表单没错误
          if (!err) {
            // 模拟后端请求 2000 毫秒延迟
            values.note = _this.content
            values.beginTime = values.validTime[0].format('YYYY-MM-DD HH:mm:ss')
            values.endTime = values.validTime[1].format('YYYY-MM-DD HH:mm:ss')
            values.id = _this.couponInfo.id
            values.value = values.value * 100

            save(values).then((res) => {
              if (res.code === 200) {
                _this.$message.success('添加成功')
                this.$emit('onGoBack')
              } else {
                this.$notification.error({
                  message: '错误',
                  description: res.message,
                  duration: 4
                })
              }
            }).catch(() => {
              // Do something
            }).finally(() => {
              _this.confirmLoading = false
            })

          }
        })

      }

    }

  }

</script>

<style>
  .ql-container {
    height: 300px;
  }
</style>